﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Noria.Net.Chaos.Net
{
    class HeadlessForwarder
    {
        private TcpClient client;
        private TcpClient server;
        private IEnumerable<IRule> rules;
        private byte[] buffer = new byte[2048];

        public HeadlessForwarder(TcpClient client, TcpClient server, IEnumerable<IRule> rules)
        {
            this.rules = rules;
            this.client = client;
            this.server = server;
        }

        internal void Start()
        {
            QuickForward();
        }

        private async void QuickForward()
        {
            // receive data from client
            if (!client.Connected)
                return;
            int received = 0;
            try
            {
                received = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
                if (received == 0)
                    return;

                if (rules != null)
                {
                    foreach (var rule in rules)
                    {
                        if (rule.Apply(buffer, ref received))
                            break;
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // cancelled
                return;
            }

            // forward to server
            if (!server.Connected)
                return;
            try
            {
                await server.GetStream().WriteAsync(buffer, 0, received);
            }
            catch (ObjectDisposedException)
            {
                // cancelled
                return;
            }

            // call the step once again
            QuickForward();
        }
    }

}
